<template>
  <div class="filter-item">
    <span>{{label}}</span>
    <div class="select-items">
      <select v-model="index">
        <option v-if="!showDefault" :value="null">请选择{{label}}</option>
        <option v-for="option in validOptions" :key="'select_option_' + option.index" :value="option.index">{{option.name}}</option>
      </select>
    </div>
    <div class="tag-items">
      <i-tag
        v-for="option in validOptions"
        v-bind:class="{'ivu-tag-blue': index == option.index}"
        :key="option.index"
        @click.native="index=option.index">{{option.name}}</i-tag>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    options: {
      type: Array
    },
    value: {
      required: true
    },
    label: {
      type: String
    },
    showDefault: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    validOptions() {
      if (!this.showDefault) return this.options
      return [{ index: null, name: '不限' }].concat(this.options)
    }
  },
  data() {
    return {
      index: null
    }
  },
  methods: {
    setValue(val) {
      if (val === this.index) return
      this.index = val
    }
  },
  watch: {
    index(val) {
      if (val === this.value) return
      this.$emit('update:value', val)
    },
    value(val) {
      this.setValue(val)
    }
  },
  mounted() {
    this.setValue(this.value)
  }
}
</script>

<style scoped lang="less">
.filter-item {
  span {
    height: 30px;
    line-height: 30px;
  }
  .select-items {
    display: none;
    select {
      display: block;
      width: 100%;
      height: 30px;
    }
  }
  @media screen and (max-width: 767px) {
    .select-items {
      display: block;
    }
    .tag-items {
      display: none;
    }
  }
}
</style>
